﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace PlaystationNetworkAPI.Core.Common
{
    internal class Collector
    {
        internal CookieContainer _CookieContainer;

        internal Collector()
        {
            _CookieContainer = new CookieContainer();
        }

        /// <summary>
        /// Create a HttpWebRequest object and setup to on general web servers.
        /// </summary>
        /// <param name="url">URL that will be used on the request.</param>
        /// <returns>HttpWebRequest setup to work on general web servers</returns>
        internal virtual System.Net.HttpWebRequest CreateHttpWebRequest(string url)
        {
            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

            httpWebRequest.UserAgent = Properties.Settings.Default.Common_Collector_Request_UserAgent;
            httpWebRequest.Accept = Properties.Settings.Default.Common_Collector_Request_Accept;
            httpWebRequest.CookieContainer = _CookieContainer;

            return httpWebRequest;
        }

        /// <summary>
        /// Get the source code of the requested pages.
        /// </summary>
        /// <param name="url">Full URL to get the source code from.</param>
        /// <returns>The returned page source code.</returns>
        internal string GetSourceCode(string url)
        {
            string sourceHtml;

            using (System.Net.HttpWebResponse httpWebResponse = (System.Net.HttpWebResponse)CreateHttpWebRequest(url).GetResponse())
            {
                using (System.IO.StreamReader streamReader = new System.IO.StreamReader(httpWebResponse.GetResponseStream()))
                {
                    sourceHtml = streamReader.ReadToEnd();
                    streamReader.Close();
                }
                httpWebResponse.Close();
            }

            return sourceHtml;
        }

    }
}
